﻿using System;
using System.Text;
using RAP.Framework.Libary.Utils;
using RAP.Framework.Libary.DomTemplateBuilder.Interface;

namespace RAP.Framework.Libary.DomTemplateBuilder.Handler
{
	/// <summary>
	/// 数据类型转换的Handler
	/// </summary>
	public class ConvertTypeHandler : PropertyElementHandler
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="rootParamObject"></param>
        /// <param name="parentParamObject"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override void DoRender ( StringBuilder writer, object rootParamObject, object parentParamObject, ITemplateRenderContext context )
        {
            var propertyName = GetPropertyName( rootParamObject, parentParamObject, context );
            object value = null;
            if ( !propertyName.IsNullOrEmpty() )
            {
                //如果是有属性名称，则将指定属性的值转换类型后存回指定属性
                foreach ( var field in propertyName.Split( ',', StringSplitOptions.RemoveEmptyEntries ) )
                {
                    value = GetExpressionValue
                    (
                        field
                        , rootParamObject
                        , parentParamObject
                        , context
                    );
                    value = GetConvertedValue( value );
                    ExpressionUtils.SetFieldValue( field, value, rootParamObject, parentParamObject, context, () =>
                    {
                        var paramObj = GetParamObject( rootParamObject, parentParamObject, context );
                        paramObj.SetValue( field, value );
                    } );
                }
            }
            else
            {
                //如果未指定属性名称，则将内部输出作为要转换的值转换类型后再输出
                var sbValue = new StringBuilder();
                var paramObject = GetParamObject( rootParamObject, parentParamObject, context );
                base.DoRenderChildNodes( sbValue, rootParamObject, paramObject, context );
                value = sbValue.ToString();
                value = GetConvertedValue( value );
                writer.Append( value );
            }
        }
    }
}
